package com.rankeiot.core.data.response;

import com.rankeiot.core.data.LocalizedMessage;
import com.rankeiot.core.exception.BusinessException;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import org.sagacity.sqltoy.model.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用响应
 * @param <T>
 * @author desire
 */
@Schema(description = "通用响应消息")
@Data
public class Resp<T> {
    @Schema(description =  "响应代码")
    protected int code=0;
    @Schema(description = "是否成功")
    protected boolean success=true;
    @Schema(description = "消息")
    protected String message;
    @Schema(description = "数据")
    protected T data;

    public static <T> Resp<T> of(T data){
        Resp ret=new Resp();
        ret.success=true;
        ret.data=data;
        return ret;
    }
    public static <T> PageResp<T> of(Page<T> data){
        PageResp ret=new PageResp();
        ret.setTotal(data.getRecordCount());
        ret.setData(data.getRows());
        return ret;
    }
    public static MapResp of(Map data){
        return new MapResp(data);
    }
    public static MapResp map(){
        return new MapResp(new HashMap());
    }
    public static <T> Resp<T> ok(){
        return ok("成功");
    }
    public static <T> Resp<T> ok(String message){
        return ok(null,message);
    }



    public static <T> Resp<T> ok(T data, String message){
        Resp ret=new Resp();
        ret.success=true;
        ret.message=message;
        ret.data=data;
        return ret;
    }
    public static void fail(LocalizedMessage message){
        fail(message.toStr());
    }
    /**
     * 处理失败，此处跑出异常
     * @param message
     */
    public static void fail(String message) throws BusinessException{
        throw new BusinessException(message.toString());
    }
    public static void fail(LocalizedMessage message, int code){
        fail(message.toStr(),code);
    }
    public static void fail(String message, int code){
        throw new BusinessException(code,message);
    }

    public static ResponseEntity<StreamingResponseBody> export(String fileName, StreamingResponseBody out){
        try {
            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"))
                    .body(out);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
